// pages/maintenance/maintenance.js

var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_img = app.globalData.applet_park_api_url_img;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statuses:1,
    currenttab:'',
    imageList: [],
    imagepreList: [],
    sources: '',
    pics: [],
    model: '',
    workid: '',
    calcontent: '',
    calcontent2: '',
    currenttab: '',
    showModal: false,
    showModal2: false,
    items: [],
    customerServiceshow: false,
    directo: false,
    title: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userRoles = wx.getStorageSync("userRoles");
    //客服
    if (userRoles.indexOf('customerService') != -1) {
      this.setData({
        customerServiceshow: true
      })
    }
    
    //主管
    if ((userRoles.indexOf('engineeringSupervisor') != -1) || (userRoles.indexOf('safetySupervisor') != -1) || (userRoles.indexOf('environmentalSupervisor') != -1)) {
      this.setData({
        directo: true
      })
      
    }
    var id = wx.getStorageSync("id");
    
    this.setData({
      sysemid: id
    })


  },
  packBp(e) {
    this.setData({
      currenttab: e.currentTarget.dataset.index
    })
  },
  delect(e) {

    var pics = this.data.pics;
    var imageList = this.data.imageList;
    var imagepreList = this.data.imagepreList;
    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    imageList.splice(index, 1);
    imagepreList.splice(index, 1);
    this.setData({
      pics: pics,
      imageList: imageList,
      imagepreList: imagepreList
    });
  },
  testSubmit(e) {
    var self = this;
    var openId = wx.getStorageSync("OPENID");
    var fId = e.detail.formId; //获取formId
    
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxcc80ff4f9e7ee858&secret=88cdd694e5804167c07f5b89b5a56d20',
      method: 'GET',
      success: function (res) {
        

        var d = {
          "keyword1": {
            "value": "00273",
            "color": "#4a4a4a"
          },
          "keyword2": {
            "value": "腾讯早餐店",
            "color": "#9b9b9b"
          },
          "keyword3": {
            "value": "66元",
            "color": "#9b9b9b"
          }

        };
        
        wx.request({
          url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' + res.data.access_token,
          // header: {
          //   'content-type': 'Content-Type: application/json;',
          // },
          data: {
            touser: openId,
            template_id: "BEaKeDwRS2aPA0xfsrbSlxh7NfFeM7rSDk5wd70_WNs", //换成你申请的模板消息id，  
            page: "pages/index/index",
            form_id: e.detail.formId,
            data: d

          },
          method: 'POST',
          success: function (res) {
            
          },
          fail: function (err) {
            
          }
        })
      },
    })
  },

  formSubmit: function (e) {
    var that = this
    
    
    wx.request({
      url: "https://xxx/mobiletplus/index.php?act=login&op=send_wx",
      data: {
        "form_id": e.detail.formId,
        "customer_id": that.data.customer_id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //util.showSuccess("设置成功")
        //

      },
      fail: function (e) {
        //util.showError("设置失败".e)
      }
    })
  },

  openzp: function (e) {
    var workid = e.currentTarget.dataset.workid;
    var model = e.currentTarget.dataset.model;
    this.setData({
      showModal: true,
      workid: workid,
      model: model,
      calcontent: '',
    })
  },
  complete: function (e) {
    var workid = e.currentTarget.dataset.workid;
    var model = e.currentTarget.dataset.model;
    this.setData({
      showModal2: true,
      workid: workid,
      model: model
    })
  },
  preventTouchMove: function () {

  },

  chooseImage_album: function (e) {

    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 3,
      success: function (res) {
        var imgsrc = res.tempFiles;
        
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc);
        // for (var obj of res.tempFiles) {
        //   obj.showOrder = that.data.showOrder;
        //   that.data.showOrder++;
        // }
        that.setData({
          pics: pics,
          imageList: imageList
        })
      }
    })
  },
  go: function () {
    this.setData({
      showModal: false
    })
  },
  go2: function () {
    this.setData({
      showModal2: false
    })
  },
  calsubmit2: function () {
    var that = this;
    var sources = '';
    wx.showLoading({
      title: '图片上传中',
      mask: true
    });
    var finished = true;
    
    // that.data.imageList = that.data.imageSingleList.concat(that.data.imageMultiList);
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }

    if (finished) {
      wx.hideLoading();

      // wx.navigateBack();
      that.submitcomplete();
      return;
    }

    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) {
      if (i >= that.data.imageList.length) {
        return;
      }

      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;

        wx.uploadFile({
          url: applet_park_api_url + '/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.data.imageList[i].picUrl = applet_park_api_url_img + response.data[0];

            sources = sources + response.data[0] + ",";
            // sources.push("https://njdhy.com.cn:7777" + response.data[0])
            
            that.data.sources = sources;
            that.setData(that.data);
            
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            if (allFinished) { //全部传完了,则隐藏加载按钮并返回
              wx.hideLoading();
              //数据回传录车页面,返回
              that.submitcomplete();
              //wx.navigateBack();
            } else {
              uploadImage(i + 1);
            }
          },
          fail(res) {
            
          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);
  },
  loadData() {
    this.setData({
      title: '数据正在加载',
    })
    let that = this;
    that.data.items = [];
    that.setData({
      items: []
    })
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      data: {
        consignorId: id,
        statuses: that.data.statuses,
      },
      success(res) {
        
        
        if (res.data.code == 0) {
          for (var row of res.data.data) {
            if (row.executionTime) {
              row.executionTime = row.executionTime.substring(0, row.executionTime.length - 2);
              // row.executionTime = row.executionTime.replace(.0,'');
            }
            that.data.items.push(row);
          }
          if (that.data.items.length == 0) {
            that.setData({
              title: '暂无更多数据',
            })
          } else {
            that.setData({

              title: ''
            })
          }
          // that.data.items=res.data.data;
          that.setData(that.data);
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },

  goToDetail() {
    // pages / maintenanceDetail / maintenanceDetail
    wx.navigateTo({
      url: '../maintenanceDetail/maintenanceDetail',
    })
  },
  //指派
  customerAppoint(e) {
    var workid = e.currentTarget.dataset.workid;
    wx, wx.navigateTo({
      url: '../assignment/assignment?workid=' + workid,
    })
  },
  //到场
  arrive(e) {
    var workid = e.currentTarget.dataset.workid;
    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: workid,
        assignorId: id,
        consignorId: id,
        status: 4
      },
      success(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
          that.loadData();
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  submitcomplete2(e) {
    var that = this;
    var workid = e.currentTarget.dataset.workid;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: workid,
        assignorId: id,
        consignorId: id,
        status: 5
      },
      success(res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
          that.loadData();
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  submitcomplete(e) {

    var that = this;
    var id = wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/repairs',
      method: "PUT",
      data: {
        id: workid,
        assignorId: id,
        consignorId: id,
        status: 5
      },
      success(res) {
        if (res.data.code == 0) {

          that.loadData();
        } else {
          wx.showToast({
            title: '网络异常',
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  gocomment(e) {
    wx.navigateTo({
      url: '../maintenanceRate/maintenanceRate?workid=' + e.currentTarget.dataset.workid,
    })
  },
  gototetail(e) {
    wx.navigateTo({
      url: '../maintenanceDetail/maintenanceDetail?workid=' + e.currentTarget.dataset.workid,
    })
  },
  radioChange: function (e) {
    
  },
  //退回
  calsubmit() {
    var that = this
    let url = '';

    if (!that.data.calcontent) {
      util.showModal('请填写退回备注');
      return
    }
    var id = wx.getStorageSync("id");

    
    if (that.data.model == 'm1') {
      url = applet_park_api_url + '/api/repairs/return'

    }

    if (that.data.model == 'm2') {
      url = applet_park_api_url + '/api/repairs/cancel'

    }

    wx.request({
      url: url,
      data: {
        repairId: that.data.workid,
        assignorId: id,
        reason: that.data.calcontent
      },
      method: 'PUT',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: function (res) {
        
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
          that.data.items = [];
          that.setData(that.data);
          that.setData({
            showModal: false
          })
          that.loadData();
        } else {

          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      },
      fail: function (e) {
        // util.showToast("网络异常")
        wx.showToast({
          title: '网络异常',
        })
      }
    })
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },
  goapplymanten() {
    wx.navigateTo({
      url: '../applyMaintenance/applyMaintenance',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.data.items = [],
    //   this.setData(this.data);
    this.loadData();
    this.loadRole();

    var userRoles = wx.getStorageSync("userRoles");
    //客服
    if (userRoles.indexOf('customerService') != -1) {
      this.setData({
        customerServiceshow: true
      })
    }
    
    //主管
    if ((userRoles.indexOf('engineeringSupervisor') != -1) || (userRoles.indexOf('safetySupervisor') != -1) || (userRoles.indexOf('environmentalSupervisor') != -1)) {
      this.setData({
        directo: true
      })
      
    }
  },
  loadRole() {
    var id = wx.getStorageSync("id");

    wx.request({
      url: applet_park_api_url + '/api/sysRoles/userRoles?sysUserId=' + id,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: function (res) {
        
        if (res.data.code == 0) {
          wx.setStorageSync("userRoles", res.data.data);
          
        } else {
          wx.showToast({
            title: '操作失败',
          })
        }
      },
      fail: function (e) {
        // util.showToast("网络异常")
        wx.showToast({
          title: '网络异常',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.data.items = [],
      this.setData(this.data);
    this.loadData();

    this.loadRole();
    var userRoles = wx.getStorageSync("userRoles");
    //客服
    if (userRoles.indexOf('customerService') != -1) {
      this.setData({
        customerServiceshow: true
      })
    }
    
    //主管
    if ((userRoles.indexOf('engineeringSupervisor') != -1) || (userRoles.indexOf('safetySupervisor') != -1) || (userRoles.indexOf('environmentalSupervisor') != -1)) {
      this.setData({
        directo: true
      })
      
    }
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 2000
    })



  },
  packBp(e) {
    this.setData({
      currenttab: e.currentTarget.dataset.index
    })
    if (e.currentTarget.dataset.index==0){
      this.setData({
        statuses: '1'
      })
    }
    if (e.currentTarget.dataset.index == 1) {
      this.setData({
        statuses: '6,7,9'
      })
    }
    if (e.currentTarget.dataset.index == 2) {
      this.setData({
        statuses: ' 2,3,4,5,8'
      })
    }
    
    this.loadData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})